package com.market.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.market.dto.ShopCartDto;
import com.market.entity.*;
import com.market.enums.RoleEnum;
import com.market.enums.StateEnum;
import com.market.exceptions.MyException;
import com.market.service.*;
import com.market.utils.SendCode;
import com.market.utils.TokenUtil;
import com.market.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName BuyerController
 * @Description TODO
 * @Author 1
 * @Date 2022/3/30 20:44
 * @Version 1.0
 */
@RestController
@RequestMapping("buyer")
public class BuyerController {
    @Autowired
    BuyerService buyerService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderService orderService;
    @Autowired
    SendBackService sendBackService;



//    发送验证码
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @GetMapping("sendCode")
    public R sendCode(String telephone) {
        //从redis获取验证码
        String code=redisTemplate.opsForValue().get(telephone);
        if(code!=null){
            try {
                SendCode.send();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new R(StateEnum.CAPTCHA_SEND_FAIL.getState(),"错误,验证码已经发送");
        }else{
            redisTemplate.opsForValue().set(telephone,"1234",60, TimeUnit.SECONDS);
             code = redisTemplate.opsForValue().get(telephone);
            return new R(StateEnum.CAPTCHA_SEND_SUCCESS.getState(), "验证码发送成功,有效时间为一分钟",code);
        }
    }

    //买家通过短信验证注册
    @PostMapping("buyerRegisterByCode/{code}")
    public R buyerRegisterByCode(Buyer buyer,@PathVariable String code) throws IOException {
        if(buyerService.buyerRegisterByCode(buyer,code)){
            return new R(StateEnum.REGISTRY_SUCCESS.getState(),"注册成功");
        }else{
            return new R(StateEnum.REGISTRY_FAIL.getState(), "注册失败");
        }
    }

    //买家通过账号密码注册
    @PostMapping("buyerRegisterByAccountAndPwd")
    public R buyerRegisterByAccountAndPwd(@RequestBody Buyer buyer) throws MyException {
        if(buyerService.buyerRegisterByAccountAndPwd(buyer)){
            return new R(StateEnum.REGISTRY_SUCCESS.getState(),"通过账号密码注册成功");
        }else{
            return new R(StateEnum.REGISTRY_FAIL.getState(), "通过账号密码注册失败");
        }
    }

    //买家根据账号密码登录
    @GetMapping("buyerLoginByUserNameAndPwd")
    public R buyerLoginByUserNameAndPwd(String account, String password, HttpServletResponse resp) throws MyException {
        Buyer buyer=buyerService.queryBuyerByAccount(account);
        if(buyerService.buyerLoginByAccountAndPwd(account,password)){
            String token = TokenUtil.getToken(buyer.getId(),24*60*60*1000, RoleEnum.BUYER.getRoleName());
            resp.setHeader("token",token);
            return new R(StateEnum.LOGIN_SUCCESS.getState(), "登录成功",token);
        }else{
            return new R(StateEnum.LOGIN_FAIL.getState(), "登录失败");
        }
    }


    //根据账号查看某个买家
    @GetMapping("queryBuyerByAccount")
    public R queryBuyerByAccount(String account){
        Buyer buyer = buyerService.queryBuyerByAccount(account);
        if(buyer!=null){
            return new R(StateEnum.QUERY_BUYER_SUCCESS.getState(), "查询买家成功",buyer);
        }else{
            return new R(StateEnum.QUERY_BUYER_FAIL.getState(), "通过账号密码注册失败");
        }
    }



    //添加或修改买家所在地址
    @GetMapping("addBuyerAddress")
    public R addBuyerAddress(int buyerId,String address){
        if(buyerService.addBuyerAddress(buyerId,address)){
            return new R(StateEnum.QUERY_BUYER_SUCCESS.getState(), "添加或修改买家所在地址成功");
        }else{
            return new R(StateEnum.UPDATE_ADDRESS_FAIL.getState(), "添加或修改买家所在地址失败");
        }
    }

    //修改基本买家信息(昵称，电话号码，地址，性别)
    @GetMapping("updateBuyerInfo")
    public R updateBuyerInfo(Integer buyerId,String nickname,String telephone,String address,String sex){
        if(buyerService.updateBuyerInfo(buyerId,nickname,telephone,address,sex)){
            return new R(StateEnum.UPDATE_BUYER_INFO_SUCCESS.getState(), "修改买家基本信息成功");
        }else{
            return new R(StateEnum.UPDATE_BUYER_INFO_FAIL.getState(), "修改买家基本信息失败");
        }
    }

    //根据商品id查询商品
    @GetMapping("queryGoods")
    public R queryGoods(int goodsId){
        Goods goods=buyerService.queryGoods(goodsId);
        if(goods!=null){
            return new R(StateEnum.QUERY_GOODS_SUCCESS.getState(), "查询商品成功",goods);
        }else{
            return new R(StateEnum.QUERY_GOODS_FAIL.getState(), "修改买家基本信息失败");
        }
    }

    // 创建空订单
    @PostMapping("createOrder")
    public R placeOrder(@RequestBody Order order){
        Buyer buyer=buyerService.queryBuyerById(order.getBuyerId());
        if(buyer.getAddress()==null){
            return new R(StateEnum.CREATE_EMPTY_ORDER_FAIL.getState(), "您还没有填写所在地址，请先填写地址再下单");
        }
        if(buyerService.createOrder(order)){
            return new R(StateEnum.CREATE_EMPTY_ORDER_SUCCESS.getState(), "创建订单成功");
        }else{
            return new R(StateEnum.CREATE_EMPTY_ORDER_FAIL.getState(), "创建订单失败");
        }
    }

    // 添加订单详情
    @PostMapping("addOrderDetail")
    public R addOrderDetail(@RequestBody OrderDetail orderDetail){
        if(orderDetailService.addOrderDetail(orderDetail)){
            return new R(StateEnum.ADD_ORDER_DETAIL_SUCCESS.getState(), "添加订单详情成功");
        }else{
            return new R(StateEnum.ADD_ORDER_DETAIL_SUCCESS.getState(), "添加订单详情失败");
        }
    }

    //付款
    @GetMapping("pay")
    public R pay(int orderId){
        if(buyerService.pay(orderId)){
            return new R(StateEnum.PAY_SUCCESS.getState(), "付款成功");
        }else{
            return new R(StateEnum.PAY_FAIL.getState(), "付款失败");
        }
    }

    //确认收货
    @GetMapping("confirmReceipt")
    public R confirmReceipt(int orderId){
        if(buyerService.confirmReceipt(orderId)){
            return new R(StateEnum.CONFIRM_RECEIPT_SUCCESS.getState(), "确认收货成功");
        }else{
            return new R(StateEnum.CONFIRM_RECEIPT_FAIL.getState(), "确认收货失败");
        }
    }

    //锁定买家
    @GetMapping("lockBuyer")
    public R lockBuyer(int buyerId){
        if(buyerService.lockBuyer(buyerId)){
            return new R(StateEnum.LOCK_BUYER_SUCCESS.getState(), "锁定买家成功");
        }else{
            return new R(StateEnum.LOCK_BUYER_FAIL.getState(), "锁定买家失败");
        }
    }

    //解锁买家
    @GetMapping("unLockBuyer")
    public R unLockBuyer(int buyerId){
        if(buyerService.unLockBuyer(buyerId)){
            return new R(StateEnum.UNLOCK_BUYER_SUCCESS.getState(), "解锁买家成功");
        }else{
            return new R(StateEnum.UNLOCK_BUYER_FAIL.getState(), "解锁买家失败");
        }
    }

    //根据买家id查询买家
    @GetMapping("queryBuyerById")
    public R queryBuyerById(int buyerId){
        Buyer buyer=buyerService.queryBuyerById(buyerId);
        if(buyer!=null){
            return new R(StateEnum.QUERY_BUYER_SUCCESS.getState(), "查询买家成功",buyer);
        }else{
            return new R(StateEnum.QUERY_BUYER_FAIL.getState(), "查询买家失败");
        }
    }

    //todo 申请退货
    @GetMapping("applyReturnGoods")
    public R applyReturnGoods(int orderId){
        if(buyerService.applyReturnGoods(orderId)){
            return new R(StateEnum.APPLY_RETURN_GOODS_SUCCESS.getState(), "退货申请发送成功");
        }else{
            return new R(StateEnum.APPLY_RETURN_GOODS_FAIL.getState(), "退货申请发送失败");
        }
    }

    //根据商品名查找某个商品
    @GetMapping("queryGoodsByGoodsName")
    public R queryGoodsByGoodsName(String goodsName){
        Goods goods=buyerService.queryGoodsByGoodsName(goodsName);
        if(goods!=null){
            return new R(StateEnum.QUERY_GOODS_SUCCESS.getState(), "查找商品成功",goods);
        }else{
            return new R(StateEnum.QUERY_GOODS_FAIL.getState(), "查找商品失败");
        }
    }

    //通过商品类别id查找商品
    @GetMapping("queryGoodsByGoodsTypeId")
    public R queryGoodsByGoodsTypeId(int goodsTypeId,int currentPage,int pageSize){
        PageHelper.startPage(currentPage, pageSize);
        List<Goods> goodsList=buyerService.queryGoodsByGoodsTypeId(goodsTypeId);
        if(goodsList!=null){
            return new R(StateEnum.QUERY_GOODS_SUCCESS.getState(),"查找商品成功",new PageInfo<>(goodsList));
        }else{
            return new R(StateEnum.QUERY_GOODS_FAIL.getState(),"查找商品失败");
        }
    }

    //买家充值
    @GetMapping("charge")
    public R charge(int buyerId,double money){
        if(buyerService.charge(buyerId,money)){
            return new R(StateEnum.CHARGE_SUCCESS.getState(), "充值成功");
        }else{
            return new R(StateEnum.CHARGE_FAIL.getState(), "充值失败");
        }
    }



    //根据小店id查看买家
    @GetMapping("queryBuyerByStoreId")
    public R queryBuyerByStoreId(int storeId,int currentPage,int pageSize){
        PageHelper.startPage(currentPage,pageSize);
        List<Buyer> buyers = buyerService.queryBuyerByStoreId(storeId);
        if(buyers!=null){
            return new R(StateEnum.QUERY_BUYER_SUCCESS.getState(), "根据小店id查看买家成功",new PageInfo<>(buyers));
        }else{
            return new R(StateEnum.QUERY_BUYER_FAIL.getState(),"根据小店id查看买家失败");
        }
    }

    //添加小店id
    @GetMapping("addStoreId")
    public R addStoreId(int buyerId,int storeId){
        if(buyerService.addStoreId(buyerId,storeId)){
            return new R(StateEnum.ADD_STORE_ID_SUCCESS.getState(), "添加小店id成功");
        }else{
            return new R(StateEnum.ADD_STORE_ID_FAIL.getState(), "添加小店id失败");
        }
    }

    //加入购物车
    @GetMapping("addToCart")
    public R addToCart(int goodsId, int goodsNum, int buyerId){
        if(buyerService.addToCart(goodsId,goodsNum,buyerId)){
            return new R(StateEnum.ADD_TO_SHOP_CART_SUCCESS.getState(), "加入购物车成功");
        }else{
            return new R(StateEnum.ADD_TO_SHOP_CART_SUCCESS.getState(),"加入购物车失败");
        }
    }

    //买家查看购物车
    @GetMapping("queryShopCart")
    public R queryShopCartByBuyerId(HttpServletRequest request){
        String token=request.getHeader("token");
        Map<String, Object> map = TokenUtil.parseToken(token);
        String buyerId=(String)map.get("id");
        int buyerId1=Integer.parseInt(buyerId);
        List<ShopCartDto> shopCarts = buyerService.queryShopCartByBuyerId(buyerId1);
        if(shopCarts.size()!=0){
            return new R(StateEnum.QUERY_SHOP_CART_SUCCESS.getState(), "查询购物车成功",shopCarts);
        }else{
            return new R(StateEnum.QUERY_SHOP_CART_FAIL.getState(),"查询购物车失败",shopCarts);
        }
    }


    //查询某个买家所有退货单
    @GetMapping("findSendBackRecords")
    public R findSendBackRecords(int buyerId){
        List<SendBack> sendBackRecords = sendBackService.findSendBackRecords(buyerId);
        if(sendBackRecords.size()!=0){
            return new R(StateEnum.QUERY_SEND_BACK_SUCCESS.getState(), "查询某个买家所有退货单成功");
        }else{
            return new R(StateEnum.QUERY_SEND_BACK_FAIL.getState(), "查询某个买家所有退货单失败");
        }
    }

    //根据token查询买家信息
    @GetMapping("queryBuyerByToken")
    public R queryBuyerByToken(HttpServletRequest rest){
        String token=rest.getHeader("token");
        Map<String, Object> map = TokenUtil.parseToken(token);
        String buyerId=(String)map.get("id");
        int buyerId1=Integer.parseInt(buyerId);
        Buyer buyer=buyerService.queryBuyerById(buyerId1);
        if(buyer!=null){
            return new R(StateEnum.QUERY_BUYER_SUCCESS.getState(), "根据token查询某个买家成功",buyer);
        }else{
            return new R(StateEnum.QUERY_BUYER_FAIL.getState(), "根据token查询某个买家失败");
        }
    }

}
